package com.example.yskjproject.adapter;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;
import android.view.View;

import androidx.annotation.Nullable;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.example.yskjproject.R;
import com.example.yskjproject.content.Content;
import com.example.yskjproject.content.EventContent;
import com.example.yskjproject.event.EventMessage;
import com.example.yskjproject.http.APIService;
import com.example.yskjproject.http.Urls;
import com.example.yskjproject.http.callback.JsonCallback;
import com.example.yskjproject.model.BooleanLoginWorksModel;
import com.example.yskjproject.model.LzyResponse;
import com.example.yskjproject.model.MessageDateModel;
import com.example.yskjproject.model.RoomLiveInfoModel;
import com.example.yskjproject.ui.activity.ClassroomWorksActivity;
import com.example.yskjproject.utils.EventBusUtil;
import com.example.yskjproject.utils.GenerateTestUserSig;
import com.example.yskjproject.utils.Log;
import com.example.yskjproject.utils.SpCashUtils;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import com.tencent.cloud.tuikit.roomkit.ConferenceObserver;
import com.tencent.qcloud.tuicore.TUILogin;
import com.tencent.qcloud.tuicore.interfaces.TUICallback;
import com.tencent.qcloud.tuicore.util.ToastUtil;

import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import es.dmoral.toasty.Toasty;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import okhttp3.MediaType;
import okhttp3.RequestBody;

/**
 * MessageAdapter  消息列表
 * <p>
 * 作者：zx
 * 创建时间：2024/4/15
 */
public class MessageAdapter extends BaseQuickAdapter<MessageDateModel, BaseViewHolder> {

    private Gson gson = new Gson();
    private Context context;

    public MessageAdapter(int layoutResId, @Nullable List<MessageDateModel> data, Context context) {
        super(layoutResId, data);
        this.context = context;
    }

    @Override
    protected void convert(BaseViewHolder helper, MessageDateModel item) {
        helper.setText(R.id.item_content, item.getMessage());
        if (item.getMessages_rose() == 1) {//用户
            if (item.getMessage_type().equals("order")) {//支付下单
                helper.getView(R.id.right_tv).setVisibility(View.VISIBLE);
                helper.setText(R.id.right_tv, "进入上课");
                helper.getView(R.id.right_tv).setOnClickListener(LoginWorks -> {
                    //验证
                    getNextWorks(item.getStudio_id());

                });
            } else if (item.getMessage_type().equals("check_refund_no")) {//拒绝退款
                helper.getView(R.id.right_tv).setVisibility(View.VISIBLE);
                helper.setText(R.id.right_tv, "官方客服");
                helper.getView(R.id.right_tv).setOnClickListener(kf -> {
                    //联系客服
                });
                helper.getView(R.id.middle_tv).setVisibility(View.VISIBLE);
                helper.setText(R.id.middle_tv, "查看订单");
                helper.getView(R.id.middle_tv).setOnClickListener(reject -> {
                    //查看订单
                    EventBusUtil.sendEvent(new EventMessage(EventContent.look_order));
                });
            } else if (item.getMessage_type().equals("check_refund_ok")) {//同意退款
                helper.getView(R.id.right_tv).setVisibility(View.VISIBLE);
                helper.setText(R.id.right_tv, "官方客服");
                helper.getView(R.id.right_tv).setOnClickListener(kf -> {
                    //联系客服
                });
                helper.getView(R.id.middle_tv).setVisibility(View.VISIBLE);
                helper.setText(R.id.middle_tv, "查看订单");
                helper.getView(R.id.middle_tv).setOnClickListener(reject -> {
                    //查看订单
                    EventBusUtil.sendEvent(new EventMessage(EventContent.look_order));
                });
            }
        } else {//教练
            if (item.getMessage_type().equals("begin_class")) {//订单被人购买
                helper.getView(R.id.middle_tv).setVisibility(View.VISIBLE);
                helper.setText(R.id.middle_tv, "查看订单");
                helper.getView(R.id.middle_tv).setOnClickListener(lookOrder -> {
                    //查看订单
                    EventBusUtil.sendEvent(new EventMessage(EventContent.look_order));
                });
                helper.getView(R.id.right_tv).setVisibility(View.VISIBLE);
                helper.setText(R.id.right_tv, "进入上课");
                helper.getView(R.id.right_tv).setOnClickListener(createWorks -> {
                    //创建直播
                    createLoginWorks(item.getStudio_id());
                });
            } else if (item.getMessage_type().equals("apply_refund ")) {//申请退款
                helper.getView(R.id.left_tv).setVisibility(View.VISIBLE);
                helper.setText(R.id.left_tv, "查看订单");
                helper.getView(R.id.left_tv).setOnClickListener(lookOrder -> {
                    //查看订单
                    EventBusUtil.sendEvent(new EventMessage(EventContent.look_order));
                });
                helper.getView(R.id.middle_tv).setVisibility(View.VISIBLE);
                helper.setText(R.id.middle_tv, "驳回");
                helper.getView(R.id.middle_tv).setOnClickListener(reject -> {
                    //不同意
                    notOrder(item.getOrder_sn());
                });
                helper.getView(R.id.right_tv).setVisibility(View.VISIBLE);
                helper.setText(R.id.right_tv, "同意");
                helper.getView(R.id.right_tv).setOnClickListener(LoginWorks -> {
                    //同意退款
                    okOrder(item.getOrder_sn());
                });
            }


        }
    }

    /**
     * 验证是否能进入工作室
     */
    private void getNextWorks(int studio_id) {
        Type type = new TypeToken<LzyResponse<BooleanLoginWorksModel>>() {
        }.getType();
        APIService.<LzyResponse<BooleanLoginWorksModel>>getData(type, Urls.CHECK_JOIN + "?studio_id=" + studio_id).subscribeOn(Schedulers.io()).map(response -> response.data).observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<BooleanLoginWorksModel>() {
            @Override
            public void onSubscribe(Disposable d) {
                Log.e("onSubscribe ： " + d);
            }

            @SuppressLint({"NotifyDataSetChanged", "UseRequireInsteadOfGet", "CheckResult"})
            @Override
            public void onNext(BooleanLoginWorksModel booleanLoginWorksModel) {
                if (booleanLoginWorksModel == null) {
                    return;
                }
                if (booleanLoginWorksModel.isJoin_enable()) {
                    // todo 可以的进去的逻辑   roomId
                    //进入直播间
                    nextLoginZB(studio_id);
                } else {
                    // 不可以进去的逻辑
                    ToastUtil.toastShortMessage(booleanLoginWorksModel.getMsg());
                }
            }


            @Override
            public void onError(Throwable e) {
                e.printStackTrace();            //请求失败
                Log.e("onError ： " + "获取失败");
            }

            @Override
            public void onComplete() {

            }
        }); //

    }

    private void nextLoginZB(int studioId) {
        OkGo.<LzyResponse<RoomLiveInfoModel>>get(Urls.LIVE_INFO + "?studio_id=" + studioId).execute(new JsonCallback<LzyResponse<RoomLiveInfoModel>>() {
            @Override
            public void onSuccess(Response<LzyResponse<RoomLiveInfoModel>> response) {
                RoomLiveInfoModel data = response.body().data;
                if (data == null) {
                    return;
                }

                TUILogin.login(context, Content.SDK_ID,     // 请替换为步骤一取到的 SDKAppID
                        data.getLive_user_id(),        // 请替换为您的 UserID
                        GenerateTestUserSig.genTestUserSig(String.valueOf(data.getLive_user_id())),  // 您可以在控制台中计算一个 UserSig 并填在这个位置
                        new TUICallback() {
                            @Override
                            public void onSuccess() {
                                Intent intent = new Intent(context, ClassroomWorksActivity.class);
                                intent.putExtra("id", data.getLive_room_id());
                                intent.putExtra("roomName", data.getStudio_info().getTitle());
                                intent.putExtra("userName", data.getLive_user_name());
                                intent.putExtra("avatar_url", data.getAvatar_url());
                                intent.putExtra("userId",data.getLive_user_id());
                                intent.putExtra("studioWork", data.getStudio_info().getId());
                                if (data.getStudio_info().getCourse_info() != null){
                                    intent.putExtra("courseId", data.getStudio_info().getCourse_info().getId());
                                }
                                intent.putExtra("enableSeatControl", false);
                                intent.putExtra("muteMicrophone", !true);
                                intent.putExtra("openCamera", true);
                                intent.putExtra("soundOnSpeaker", true);
                                intent.putExtra("isCreate", false);
                                context.startActivity(intent);
                            }

                            @SuppressLint("CheckResult")
                            @Override
                            public void onError(int errorCode, String errorMessage) {
                                ToastUtil.toastShortMessage(errorMessage);
                            }
                        });


            }

            @Override
            public void onError(Response<LzyResponse<RoomLiveInfoModel>> response) {
                super.onError(response);
            }
        });
    }

    private void createLoginWorks(int studioId) {
        OkGo.<LzyResponse<RoomLiveInfoModel>>get(Urls.LIVE_INFO + "?studio_id=" + studioId).execute(new JsonCallback<LzyResponse<RoomLiveInfoModel>>() {
            @Override
            public void onSuccess(Response<LzyResponse<RoomLiveInfoModel>> response) {
                RoomLiveInfoModel data = response.body().data;
                if (data == null) {
                    return;
                }
                TUILogin.login(context, Content.SDK_ID,     // 请替换为步骤一取到的 SDKAppID
                        data.getLive_user_id(),        // 请替换为您的 UserID
                        GenerateTestUserSig.genTestUserSig(String.valueOf(SpCashUtils.getInstance().getUserId())),  // 您可以在控制台中计算一个 UserSig 并填在这个位置
                        new TUICallback() {
                            @Override
                            public void onSuccess() {
                                Intent intent = new Intent(context, ClassroomWorksActivity.class);
                                intent.putExtra("id", data.getLive_room_id());
                                intent.putExtra("roomName", data.getStudio_info().getCourse_info().getCourse_name());
                                intent.putExtra("userName", data.getLive_user_name());
                                intent.putExtra("avatar_url", data.getAvatar_url());
                                intent.putExtra("userId",data.getLive_user_id());
                                intent.putExtra("enableSeatControl", false);
                                intent.putExtra("muteMicrophone", !true);
                                intent.putExtra("openCamera", true);
                                intent.putExtra("soundOnSpeaker", true);
                                intent.putExtra("isCreate", true);
                                context.startActivity(intent);
                            }

                            @SuppressLint("CheckResult")
                            @Override
                            public void onError(int errorCode, String errorMessage) {
                                ToastUtil.toastShortMessage(errorMessage);
                            }

                        });

            }

            @Override
            public void onError(Response<LzyResponse<RoomLiveInfoModel>> response) {
                super.onError(response);
            }
        });
    }

    private void okOrder(String orderSn) {
        Map<String, Object> jsonParams = new HashMap<>();
        jsonParams.put("order_sn", orderSn);
        jsonParams.put("state", 2);
        String paramsDate = gson.toJson(jsonParams);
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), paramsDate);
        OkGo.<LzyResponse>post(Urls.OK_ORDER).upRequestBody(requestBody).execute(new JsonCallback<LzyResponse>() {
            @SuppressLint("CheckResult")
            @Override
            public void onSuccess(Response<LzyResponse> response) {
                if (response.body().code == 0) {
                    Toasty.success(context, response.body().msg);
                } else {
                    Toasty.error(context, response.body().msg);
                }
            }

            @Override
            public void onError(Response<LzyResponse> response) {
                super.onError(response);
            }
        });
    }

    private void notOrder(String order_sn) {
        Map<String, Object> jsonParams = new HashMap<>();
        jsonParams.put("order_sn", order_sn);
        String paramsDate = gson.toJson(jsonParams);
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), paramsDate);
        OkGo.<LzyResponse>post(Urls.NO_ORDER).upRequestBody(requestBody).execute(new JsonCallback<LzyResponse>() {
            @SuppressLint("CheckResult")
            @Override
            public void onSuccess(Response<LzyResponse> response) {
                if (response.body().code == 0) {
                    Toasty.success(context, "退款成功！");
                } else {
                    Toasty.error(context, response.body().msg);
                }

            }

            @Override
            public void onError(Response<LzyResponse> response) {
                super.onError(response);
            }
        });
    }
}
